package com.pig4cloud.pig.module.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.mer.Mer;
import com.pig4cloud.pig.module.api.entity.product.MallGroupProduct;
import com.pig4cloud.pig.module.api.entity.product.Product;
import com.pig4cloud.pig.module.service.mer.IMerService;
import com.pig4cloud.pig.module.service.product.IMallGroupProductService;
import com.pig4cloud.pig.module.service.product.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 拼团商品列Controller
 *
 * @author ruoyi
 * @date 2022-11-05
 */
@Validated
@Api(value = "拼团商品列控制器", tags = {"拼团商品列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/group/product")
public class MallGroupProductController {

    private final IMallGroupProductService mallGroupProductService;
	private final IMerService merService;
	private final IProductService productService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;
    /**
     * 查询拼团商品列列表
     */
    @ApiOperation("查询拼团商品列列表")
    @PreAuthorize("@pms.hasPermission('module:group:list')")
    @GetMapping("/list")
    public TableDataInfo<MallGroupProduct> list(@Validated MallGroupProduct mallGroupProduct) {
        QueryWrapper<MallGroupProduct> qw = new QueryWrapper<>();
        if(mallGroupProduct.getState() !=null){
        	qw.eq("state",mallGroupProduct.getState());
		}
        if(StrUtil.isNotEmpty(mallGroupProduct.getTitle())){
        	qw.like("title", mallGroupProduct.getTitle());
		}
        qw.orderByDesc("id");

        TableDataInfo<MallGroupProduct> td = PageUtils.buildDataInfo(mallGroupProductService.page(PageUtils.buildPage(),qw));
        List<MallGroupProduct> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (MallGroupProduct groupProduct : list){
				Product product = productService.goodsDetail(groupProduct.getLinkId());
				groupProduct.setProduct(product);
				if(StrUtil.isNotEmpty(groupProduct.getActiveImg())){
					groupProduct.setActiveImgPath(imgUrl + groupProduct.getActiveImg());
				}
			}
		}
        return td;
    }

    /**
     * 导出拼团商品列列表
     */
    @ApiOperation("导出拼团商品列列表")
    @PreAuthorize("@pms.hasPermission('module:group:export')")
    @SysLog("拼团商品列")
    @GetMapping("/export")
    public List export(@Validated MallGroupProduct mallGroupProduct) {
        List<MallGroupProduct> list = mallGroupProductService.list();
        // ExcelUtil<MallGroupProduct> util = new // ExcelUtil<MallGroupProduct>(MallGroupProduct.class);
        return  list;// util.exportExcel(list, "拼团商品列");
    }

    /**
     * 获取拼团商品列详细信息
     */
    @ApiOperation("获取拼团商品列详细信息")
    @PreAuthorize("@pms.hasPermission('module:group:query')")
    @GetMapping("/{id}")
    public R<MallGroupProduct> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        MallGroupProduct mallGroupProduct = mallGroupProductService.getById(id);
        if(mallGroupProduct!=null){
        	if(StrUtil.isNotEmpty(mallGroupProduct.getActiveImg())){
				mallGroupProduct.setActiveImgPath( imgUrl + mallGroupProduct.getActiveImg());
			}

        	if(mallGroupProduct.getLinkId() != null && mallGroupProduct.getLinkId() > 0){
				Product product = productService.goodsDetail(Long.parseLong(String.valueOf(mallGroupProduct.getLinkId())));
				mallGroupProduct.setProduct(product);
			}

			if(mallGroupProduct.getCateChildId()!=null && mallGroupProduct.getCateChildId() > 0){
				QueryWrapper<Mer> qw = new QueryWrapper<>();
				if(mallGroupProduct.getCateChildId()!=null){
					qw.eq("cate_child_id",mallGroupProduct.getCateChildId());
				}
				List<Mer> list = merService.list(qw);
				list.forEach(mer1 -> {
					if(StrUtil.isNotEmpty(mer1.getShopLogo())){
						mer1.setShopLogoPath(imgUrl + mer1.getShopLogo());
					}else{
						mer1.setShopLogoPath("");
					}
					QueryWrapper<Product> qwPro = new QueryWrapper<>();
					qwPro.eq("mer_id",mer1.getId());
					qwPro.eq("is_show",1);
					long productCount = productService.count(qwPro);
					mer1.setProductCount(productCount);
				});
				mallGroupProduct.setMerList(list);
			}

			if(mallGroupProduct.getBeginTime()!=null && mallGroupProduct.getEndTime() !=null) {
				String[] dateRange = {DateUtils.getDayByDate(mallGroupProduct.getBeginTime()),DateUtils.getDayByDate(mallGroupProduct.getEndTime())} ;
				mallGroupProduct.setDateRange(dateRange);
			}
		}
        return R.ok(mallGroupProduct);
    }

    /**
     * 新增拼团商品列
     */
    @ApiOperation("新增拼团商品列")
    @PreAuthorize("@pms.hasPermission('module:group:add')")
    @SysLog("拼团商品列")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody MallGroupProduct mallGroupProduct) {
        return R.okByRow(mallGroupProductService.save(mallGroupProduct) ? 1 : 0);
    }

    /**
     * 修改拼团商品列
     */
    @ApiOperation("修改拼团商品列")
    @PreAuthorize("@pms.hasPermission('module:group:edit')")
    @SysLog("拼团商品列")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody MallGroupProduct mallGroupProduct) {
        return R.okByRow(mallGroupProductService.updateById(mallGroupProduct) ? 1 : 0);
    }

    /**
     * 删除拼团商品列
     */
    @ApiOperation("删除拼团商品列")
    @PreAuthorize("@pms.hasPermission('module:group:remove')")
    @SysLog("拼团商品列")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(mallGroupProductService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
